<template>
    <div>
        <r-search :searchHandle="searchHandleAdd" />
        <r-search :searchForm="searchForm" :searchHandle="searchHandle" :searchData="searchData" />
        <r-table :isSelection="false" :isIndex="true" :isPagination="true" :tableData="tableData" :tableCols="tableCols" :tablePage="tablePage" @refresh="init()"></r-table>

        <r-form labelWidth="150px" :isHandle="true" :formRules="formRules" :formCols="formCols" :formHandle="formHandle" :formData="formData" ref="elForm" :inline="false" dialogWidth="850px">
            <!--            <div :slot="'door'+(index+1)" v-for="(item,index) in callLists" :key="index">-->
            <!--                <span v-for="(item2,index2) in item" :key="index2" style="margin-right:10px;margin-bottom:10px;float:left;cursor: pointer;">-->
            <!--                    <el-tag @click="callClick(item2,index)" :type="item2.type">{{index2+1}}号称</el-tag>-->
            <!--                </span>-->
            <!--            </div>-->

            <div slot="slot3">
                <div id="searchResultPanel" style="border:1px solid #C0C0C0;width:150px;height:auto; display:none;"></div>
                <p>点击地图拾取坐标 经度：{{formData.longitude}} 纬度：{{formData.latitude}}</p>
                <div id="l-map"></div>
            </div>

        </r-form>
        <r-form :formRules="formRulesEditPsw" :formHandle="formHandleEditPsw" :formData="formDataEditPsw" :formCols="formColsEditPsw" ref="elFormEditPsw" labelWidth="200px" dialogWidth="1000px" :isHandle="true" />
        <r-form :formRules="formRulesActive" :formHandle="formHandleActive" :formData="formDataActive" :formCols="formColsActive" ref="elFormActive" labelWidth="200px" dialogWidth="1000px" :isHandle="true" />

    </div>
</template>

<script>
import baidumap from "../js/baidumap";
export default {
    data() {
        var checkpass = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请再次输入密码'));
            } else if (value !== this.formData.password) {
                callback(new Error('两次输入密码不一致!'));
            } else {
                callback();
            }
        };
        var checkpass2 = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请再次输入密码'));
            } else if (value !== this.formDataEditPsw.password) {
                callback(new Error('两次输入密码不一致!'));
            } else {
                callback();
            }
        };
        return {
            baiduMap: null,
            //
            searchData: {
            },
            searchForm: [
                {
                    type: 'input',
                    prop: 'name',
                    placeholder: '商家名称',
                    width: 150
                },
                {
                    type: 'input',
                    prop: 'phone',
                    placeholder: '联系方式',
                    width: 150
                },
                {
                    type: 'input',
                    prop: 'agentName',
                    placeholder: '代理商名称',
                    width: 170,
                    isShow: e => sessionStorage.getItem('role') == 3 ? false : true
                },
                {
                    type: 'select',
                    prop: 'state',
                    placeholder: '状态',
                    width: 150,
                    options: [
                        {
                            label: '启用',
                            value: '1'
                        },
                        {
                            label: '禁用',
                            value: '2',
                        },
                    ]
                },
            ],
            searchHandleAdd: [
                {
                    label: "新增商家",
                    type: "success",
                    icon: "el-icon-circle-plus-outline",
                    handle: e => this.createdAcc(),
                    isShow: () => this.apis.showBtn(45, this)
                },
            ],
            searchHandle: [
                {
                    label: '搜索',
                    type: 'success',
                    icon: 'el-icon-search',
                    handle: e => this.init()
                },
                {
                    label: '重置',
                    icon: 'el-icon-refresh-right',
                    handle: e => this.searchFromReset()
                }
            ],
            tableData: [],
            tableCols: [
                {
                    label: '商家名称',
                    prop: 'name',
                    // theme: e => e.status ? 'primary' : 'danger', type: "tag",
                },
                {
                    label: '联系方式',
                    prop: 'phone'
                },
                {
                    label: '登录账号',
                    prop: 'account'
                },
                {
                    label: '所属上级',
                    prop: 'regionName'
                },
                {
                    label: '总收益',
                    prop: 'totalRevenue'
                },
                {
                    label: '可提余额',
                    prop: 'withdrawMoney'
                },
                {
                    label: '账号状态',
                    prop: 'state',
                    formatter: e => e.state == 1 ? '启用' : '禁用',
                    theme: e => e.state == 1 ? 'primary' : 'danger',
                    type: "tag",
                },
                {
                    label: "操作",
                    type: "button",
                    width: 400,
                    dropList: [
                        { label: "禁用账号", isShow: e => e.state == 1 && this.apis.showBtn(48, this) ? true : false },
                        { label: "恢复账号", isShow: e => e.state == 2 && this.apis.showBtn(48, this) ? true : false },
                        { label: "修改密码", isShow: () => this.apis.showBtn(49, this) },
                        { label: "删除", isShow: () => this.apis.showBtn(50, this) },
                    ],
                    dropSize: 'mini',
                    handleCommand: e => {
                        if (e.btn == '禁用账号' || e.btn == '恢复账号') {
                            this.elFormDetailActive(e.row)
                        }
                        else if (e.btn == '修改密码') {
                            this.elFormDetailEditPsw(e.row)
                        }
                        else if (e.btn == '删除') {
                            this.TableDel('/merchant', { id: e.row.id }, 'del')
                        }
                    },
                    btnList: [
                        {
                            label: '编辑',
                            type: 'primary',
                            // isShow: e => e.orderId == '123' ? true : false,
                            handle: (row) => this.createdAcc(row),
                            isShow: () => this.apis.showBtn(46, this)
                        },
                        {
                            label: '账号详情',
                            type: 'primary',
                            handle: (row) => { this.$router.push({ path: '/shop-sallerDetail', query: { id: row.id } }) },
                            isShow: () => this.apis.showBtn(47, this)
                        }
                    ]
                },

            ],
            tablePage: { limit: 10, page: 1, total: 0 },
            formData: {
                name: "",
                phone: "",
                regionalId: "",
                account: "",
                password: "",
                enterPassword: "",
                proportion: "",
                proportion2: "",
                proportion3: "",
                proportion4: "",
                address: "",
                roleName: "",
                longitude: "",
                latitude: "",
                city: ""
            },
            formCols: [
                { type: "input", label: "商家名称", placeholder: '请输入商家名称', width: 350, prop: "name", },
                { type: "input", label: "联系方式", placeholder: '请输入联系方式', width: 200, prop: "phone", },
                { type: "select", label: "所属代理商", placeholder: '请选择代理商', width: 350, prop: "regionalId", options: [] },
                { type: "input", label: " 登录账号", placeholder: '请输入登录账号', width: 350, prop: "account" },
                {                    type: "input", isShow: () => {
                        return this.formData.id ? false : true
                    }, label: " 密码", placeholder: '请输入密码', width: 350, prop: "password"                },
                {                    type: "input", isShow: () => {
                        return this.formData.id ? false : true
                    }, label: "确认密码", placeholder: '请输入确认密码', width: 350, prop: "enterPassword"                },
                { type: "input", label: "生鲜柜分成比例", placeholder: '请输入生鲜柜分成比例', width: 350, prop: "proportion", remark: '%' },
                { type: "input", label: "自提商城分成比例", placeholder: '请输入', width: 350, prop: "proportion2", remark: '%' },
                { type: "input", label: "售袋分成比例", placeholder: '请输入售袋分成比例', width: 350, prop: "proportion3", remark: '%' },
                { type: "input", label: "售卡分成比例", placeholder: '请输入售卡分成比例', width: 350, prop: "proportion4", remark: '%' },
                { type: "input", id: 'suggestId', label: "详细地址", width: 350, prop: "address" },
                { type: "slot", name: 'slot3', label: '', prop: "longitude" },
            ],
            formRules: {
                name: [
                    { required: true, message: '请输入商家人员名称', trigger: 'blur' },
                ],
                phone: [
                    { required: true, message: '请输入联系方式', trigger: 'blur' },
                ],
                regionalId: [
                    { required: true, message: '请选择所属代理商', trigger: 'blur' },
                ],
                account: [
                    { required: true, message: '请输入登录账号', trigger: 'blur' },
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur', isShow: () => { return this.formData.id ? false : true }, },

                ],
                enterPassword: [
                    { required: true, validator: checkpass, message: '请确认两次密码是否一致', trigger: 'blur', isShow: () => { return this.formData.id ? false : true }, },
                ],

                proportion: [
                    { required: true, message: '请输入生鲜柜分成', trigger: 'blur' },
                ],
                proportion2: [
                    { required: true, message: '请输入', trigger: 'blur' },
                ],
                proportion3: [
                    { required: true, message: '请输入售袋分成', trigger: 'blur' },
                ],
                proportion4: [
                    { required: true, message: '请输入售卡分成', trigger: 'blur' },
                ],
                address: [
                    { required: true, message: '请输入详细地址', trigger: 'blur' },
                ],
                longitude: [
                    { required: true, message: '请点击地图选择经纬度', trigger: 'blur' },
                ]
            },
            formHandle: [
                {
                    label: "取消",
                    handle: e => this.elFormVisible(),
                },
                {
                    label: "确定",
                    type: "success",
                    handle: e => this.elFormSubmit(),
                },

            ],
            //密码
            formDataEditPsw: {
                password: "",
                enterPassword: "",
            },
            formColsEditPsw: [
                { type: "input", label: " 密码", placeholder: '请输入密码', width: 350, prop: "password" },
                { type: "input", label: "确认密码", placeholder: '请输入确认密码', width: 350, prop: "enterPassword" },
            ],
            formRulesEditPsw: {
                password: [
                    { required: true, message: '密码', trigger: 'blur' },
                ],
                enterPassword: [
                    { required: true, validator: checkpass2, message: '请确认两次密码是否一致', trigger: 'blur' },
                ],
            },
            formHandleEditPsw: [
                {
                    label: "取消",
                    handle: e => this.elFormVisibleEditPsw(),
                },
                {
                    label: "确定",
                    type: "success",
                    handle: e => this.elFormSubmitEditPsw(),
                },

            ],
            //禁用恢复
            formDataActive: {
                isActive: "",
            },
            formRulesActive: {

            },
            formColsActive: [
                { label: "是否恢复/禁用选定账号", width: 350, prop: "isActive" },
                // { type: "input", label: "确认密码", placeholder: '请输入确认密码', width: 350, prop: "enterPassword" },
            ],
            formHandleActive: [
                {
                    label: "取消",
                    handle: e => this.elFormVisibleActive(),
                },
                {
                    label: "确定",
                    type: "primary",
                    handle: e => this.elFormSubmitActive(),
                },
            ],
            checkBox: [],

            callLists: [[], []]
        };
    },
    created() { },
    mounted() {

        this.init()
    },
    methods: {
        async init() {
            this.tablePage.offset = this.tablePage.page
            let param = { ...this.tablePage, ...this.searchData }
            let res = await this.api.merchant(param)
            if (res) {
                this.tableData = res.data.list
                this.tablePage.total = res.data.total;
            }
            let resOpt = await this.api.getOperatorList({})
            if (resOpt) {
                this.operatorId = resOpt.data.operatorId
            }
            let resAgent = await this.api.agentlist({})
            if (resAgent) {
                this.formCols[2].options = []
                for (let i = 0; i < resAgent.data.length; i++) {
                    this.formCols[2].options.push({
                        name: resAgent.data[i].name,
                        value: resAgent.data[i].id
                    })
                }
            }
        },
        callClick(item, index) {
            console.log(item);
            console.log(index);
            for (var i = 0; i < this.callLists.length; i++) {

            }
            item.type = 'success';
        },
        map() {
            var that = this;
            var map = baidumap(that);
            this.baiduMap = map;
            var geoc = new BMap.Geocoder();
            map.addEventListener("click", function (e) {
                that.formData.longitude = e.point.lng;
                that.formData.latitude = e.point.lat;

                var pt = e.point;
                geoc.getLocation(pt, function (rs) {
                    var addComp = rs.addressComponents;
                    that.formData.city = addComp.city;
                    // alert(addComp.province + ", " + addComp.city + ", " + addComp.district + ", " + addComp.street + ", " + addComp.streetNumber);
                });

            });
            map.enableScrollWheelZoom();   //启用滚轮放大缩小，默认禁用
            map.enableContinuousZoom();    //启用地图惯性拖拽，默认禁用
            return new Promise((resolve, reject) => {
                setTimeout(() => {
                    resolve();
                }, 10)

            })
        },
        createdAcc(row) {

            this.elFormVisible().then(res => {
                this.map().then(res => {
                    if (row) {
                        Object.keys(this.formData).forEach(key => {
                            this.formData[key] = row[key]
                        })
                        this.formData.id = row.id;
                        this.formData.password = ''
                    }
                });
            })

        },
        elFormSubmit() {
            this.$refs.elForm.$refs.ruleForm.validate(async (valid) => {
                if (valid) {
                    if (this.formData.id) {
                        let res = await this.api.merchantedit(this.formData)
                        if (res) {
                            this.init()
                            this.elFormVisible()
                        }
                    } else {
                        let res = await this.api.merchantadd(this.formData)
                        if (res) {
                            this.init()
                            this.elFormVisible()
                        }
                    }

                }
            });
        },
        elFormDetail(row) {

            // this.elFormVisible()
        },
        elFormDetailEditPsw(row) {
            Object.keys(this.formDataEditPsw).forEach(key => {
                this.formDataEditPsw[key] = row[key]
            })
            this.formDataEditPsw.id = row.id;
            this.formDataEditPsw.regionalId = row.regionalId;
            this.formDataEditPsw.name = row.name;
            this.formDataEditPsw.phone = row.phone;
            this.formDataEditPsw.address = row.address;
            this.formDataEditPsw.longitude = row.longitude;
            this.formDataEditPsw.latitude = row.latitude;
            this.elFormVisibleEditPsw()
        },
        async elFormSubmitEditPsw() {
            let res = await this.api.merchantedit(this.formDataEditPsw)
            if (res) {
                this.init()
                this.elFormVisibleEditPsw()
            }
        },
        elFormVisibleEditPsw(tit) {
            if (this.$refs.elFormEditPsw.$refs.ruleFormEditPsw) {
                this.$refs.elFormEditPsw.$refs.ruleFormEditPsw.resetFields()
                this.$data.formDataEditPsw = this.$options.data.call(this).formDataEditPsw;
            }
            this.$refs.elFormEditPsw.dialogFormVisible = !this.$refs.elFormEditPsw.dialogFormVisible
            this.$refs.elFormEditPsw.dialogFormTitle = tit ? tit : this.formDataEditPsw.id ? '编辑' : '新增'

            if (this.$refs.elFormEditPsw.dialogFormVisible) {
                return new Promise((resolve, reject) => {
                    setTimeout(() => {
                        resolve();
                    }, 2000)
                })
            }

        },
        elFormDetailActive(row) {
            Object.keys(this.formDataActive).forEach(key => {
                this.formDataActive[key] = row[key]
            })
            this.formDataActive.id = row.id;
            this.elFormVisibleActive()
        },
        elFormVisibleActive(tit) {
            if (this.$refs.elFormActive.$refs.ruleFormActive) {
                this.$refs.elFormActive.$refs.ruleFormActive.resetFields()
                this.$data.formDataActive = this.$options.data.call(this).formDataActive;
            }
            this.$refs.elFormActive.dialogFormVisible = !this.$refs.elFormActive.dialogFormVisible
            this.$refs.elFormActive.dialogFormTitle = tit ? tit : this.formDataActive.id ? '编辑' : '新增'

            if (this.$refs.elFormActive.dialogFormVisible) {
                return new Promise((resolve, reject) => {
                    setTimeout(() => {
                        resolve();
                    }, 2000)
                })
            }
        },
        async elFormSubmitActive() {
            // console.log(this.formDataActive.id);
            let res = await this.api.merchantchange(this.formDataActive)
            if (res) {
                this.init()
                this.elFormVisibleActive()
            }
        }
    },
};
</script>

<style scoped lang="scss">
#l-map {
  height: 250px;
  width: 100%;
}
#r-result {
  width: 100%;
}
</style>
